package com.gpt.article.controller;

import java.io.File;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import chatgpt.ChatGPT;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelWriter;
import com.gpt.article.domain.TxtClassify;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.gpt.article.domain.Lawyer;
import com.gpt.article.service.ILawyerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 律师信息Controller
 * 
 * @author zhuzi
 * @date 2023-12-29
 */
@RestController
@RequestMapping("/article/lawyer")
public class LawyerController extends BaseController
{
    @Autowired
    private ILawyerService lawyerService;
    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询律师信息列表
     */
    @PreAuthorize("@ss.hasPermi('article:lawyer:list')")
    @GetMapping("/list")
    public TableDataInfo list(Lawyer lawyer)
    {
        startPage();
        List<Lawyer> list = lawyerService.selectLawyerList(lawyer);
        return getDataTable(list);
    }

    /**
     * 导出律师信息列表
     */
    @PreAuthorize("@ss.hasPermi('article:lawyer:export')")
    @Log(title = "律师信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Lawyer lawyer)
    {
        List<Lawyer> list = lawyerService.selectLawyerList(lawyer);
        ExcelUtil<Lawyer> util = new ExcelUtil<Lawyer>(Lawyer.class);
        util.exportExcel(response, list, "律师信息数据");
    }

    /**
     * 获取律师信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('article:lawyer:query')")
    @GetMapping(value = "/{userid}")
    public AjaxResult getInfo(@PathVariable("userid") Long userid)
    {
        return success(lawyerService.selectLawyerByUserid(userid));
    }

    /**
     * 新增律师信息
     */
    @PreAuthorize("@ss.hasPermi('article:lawyer:add')")
    @Log(title = "律师信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Lawyer lawyer)
    {
        return toAjax(lawyerService.insertLawyer(lawyer));
    }

    /**
     * 修改律师信息
     */
    @PreAuthorize("@ss.hasPermi('article:lawyer:edit')")
    @Log(title = "律师信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Lawyer lawyer)
    {
        return toAjax(lawyerService.updateLawyer(lawyer));
    }

    /**
     * 删除律师信息
     */
    @PreAuthorize("@ss.hasPermi('article:lawyer:remove')")
    @Log(title = "律师信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userids}")
    public AjaxResult remove(@PathVariable Long[] userids)
    {
        return toAjax(lawyerService.deleteLawyerByUserids(userids));
    }


    /**
     * 生成
     * @return
     * @throws Exception
     */
//    @GetMapping(value = "/genInfo")
    @PostMapping("/genInfo")
    public AjaxResult genInfo()
    {
//        Lawyer lawyer = new Lawyer();
//        List<Lawyer> lawyerList = lawyerService.selectLawyerListNogen(lawyer);
//        String prompts ="";
//        ChatGPT chatGPT = null;
//        String res = "";
//        String user_name = "";
//        String law_firms = "";
//        for(Lawyer li:lawyerList){
//            System.out.println(li.getUserName());
//            System.out.println(li.getLawFirms());
//            String screen_name = li.getScreenName();
//            String verified_reason = li.getVerifiedReason();
//            String description = li.getDescription();
//
//            prompts =  "提取下面内容中律师的姓名和律师事务所全称，格式必须是：律师姓名/律师事务所名称，律师名字不要带律师两个字，如果其中一个没找到则该名称为无，直接告诉姓名/律师事务所全称（中间用/隔开） 即可，回答字数不能超过20个字。内容："
//                    +screen_name+","+verified_reason+","+description;
//            chatGPT = ChatGPT.builder()
//                    .apiKey("sk-64zKz69svXDWdkfQA66d79C009F947F8A658E1Dd5292E2Ab")
//                    .timeout(900)
//                    .apiHost("https://hixtebrwfjyc.cloud.sealos.io/") //代理地址
//                    .build()
//                    .init();
//            try {
//                res = chatGPT.chat(prompts);
//            }catch (Exception e){
//                System.out.println(e.getMessage());
//            }
//            System.out.println(screen_name+"-提取-："+res);
//            String rs[] = res.split("/");
//            if(rs.length>0){
//                user_name =rs[0];
//            }
//            if(rs.length>1){
//                law_firms =rs[1];
//            }
//            li.setUserName(user_name);
//            li.setLawFirms(law_firms);
//            lawyerService.updateLawyer(li);
//        }

        tomatch();
        return success();
    }

    /**
     * 上传待分类内容
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "上传待分类内容", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
//
        String operName = getUsername();
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", url);
        ajax.put("fileName", fileName);
        ajax.put("newFileName", FileUtils.getName(fileName));
        ajax.put("originalFilename", file.getOriginalFilename());
        System.out.println(filePath + "/" + fileName);
        //解析文件
        System.out.println(filePath + "--");
        String tmpfilePath = filePath + fileName.replaceAll("/profile/upload", "");
        File excelFile = new File(tmpfilePath);
        ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(excelFile);
        List<Map<String, Object>> maps = reader.readAll();
        Lawyer lawyer = null;


        String  userid = "";
        String  screen_name = "";
        String  verified_reason = "";
        String  description = "";
        String  user_name = "";
        String  law_firms  = "";
//        String is_match = "";

        for(Map map:maps){
            userid = String.valueOf(map.get("userid"));
            screen_name = String.valueOf(map.get("screen_name"));
            verified_reason = String.valueOf(map.get("verified_reason"));
            description = String.valueOf(map.get("description"));
            user_name = String.valueOf(map.get("user_name"));
            law_firms = String.valueOf(map.get("law_firms"));
            lawyer = new Lawyer();
            lawyer.setUserid(Long.valueOf(userid));
            lawyer.setScreenName(screen_name);
            lawyer.setVerifiedReason(verified_reason);
            lawyer.setDescription(description);
            lawyer.setUserName(user_name);
            lawyer.setLawFirms(law_firms);
            try{
                lawyerService.insertLawyer(lawyer);
            }catch (Exception e){

                System.out.println(lawyer.getScreenName()+"~~~");
                System.out.println(e.getMessage());
            }

        }
        reader.close();
//        new ClassTaskTest().importExl();
        return success("成功");
    }



    public  void tomatch() {

        List<Lawyer> list = lawyerService.selectLawyerList(new Lawyer());
        String lawNamePath = "E:\\git-test\\class_task\\lawyer_name.xlsx";

        File lawFile = new File(lawNamePath);
        ExcelReader lawReader = cn.hutool.poi.excel.ExcelUtil.getReader(lawFile);
        List<Map<String, Object>> lawnamemaps = lawReader.readAll();
        List<String> lawNames = new ArrayList<String>();
        for(Map<String, Object> lmap:lawnamemaps){
            Set<String> set = lmap.keySet();
            for(String key:set){
//                System.out.println(key+"-->"+map.get(key));
                String name  =String.valueOf( lmap.get(key));
                lawNames.add(name);
                break;
            }
        }

        Long  userid = 0l;
        String  screen_name = "";
        String  verified_reason = "";
        String  description = "";
        String  user_name = "";
        String  law_firms  = "";
        String is_match = "";
        ArrayList<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
        Map<String, Object> row1 = null;
        for(Lawyer lawyer:list){
//            userid = String.valueOf(map.get("userid"));
//            screen_name = String.valueOf(map.get("screen_name"));
//            verified_reason = String.valueOf(map.get("verified_reason"));
//            description = String.valueOf(map.get("description"));
//            user_name = String.valueOf(map.get("user_name"));
//            law_firms = String.valueOf(map.get("law_firms"));

            userid = lawyer.getUserid();
            screen_name =  lawyer.getScreenName();
            verified_reason = lawyer.getVerifiedReason();
            description = lawyer.getDescription();
            user_name =  lawyer.getUserName();
            law_firms = lawyer.getLawFirms();

            boolean isHas = lawNames.contains(user_name);
            if(isHas){
                is_match = "是";
            }else{
                is_match = "否";
            }
            row1 = new LinkedHashMap<>();
            row1.put("userid",userid);
            row1.put("screen_name",screen_name);
            row1.put("verified_reason",verified_reason);
            row1.put("description",description);
            row1.put("user_name",user_name);
            row1.put("law_firms",law_firms);
            row1.put("is_match",is_match);
            rows.add(row1);
        }

        //创建excel
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter("d:/test33.xlsx");
// 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
// 关闭writer，释放内存
        writer.close();
//        reader.close();
    }


}
